package net.bluemind.ysnp.impl;

import java.io.IOException;

import net.bluemind.unixsocket.SocketClosedException;
import net.bluemind.unixsocket.UnixDomainSocketChannel;
import net.bluemind.unixsocket.UnixServerSocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainLoop extends Thread {

	private static final Logger logger = LoggerFactory
			.getLogger(MainLoop.class);

	private UnixServerSocket socket;
	private IConnectionListener listener;

	public MainLoop(UnixServerSocket socket, IConnectionListener listener) {
		this.socket = socket;
		this.listener = listener;
	}

	@Override
	public void run() {
		boolean stopped = false;
		while (!stopped) {
			try {
				UnixDomainSocketChannel channel = socket.accept();
				listener.connectionAccepted(channel);
			} catch (SocketClosedException sce) {
				logger.info("gracefull shutdown initiated.");
			} catch (IOException ioe) {
				logger
						.error(
								"problem accepting connections, leaving main loop",
								ioe);
				return;
			}
		}
	}

	public void shutdown() throws IOException {
		socket.close();
	}

}
